import { FindOptions, MongoClient } from "mongodb";

const url = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(url);

const records = [
  {
    name: "Westbrook",
    age: 32,
  },
  {
    name: "Howard",
    age: 35,
  },
];

async function run() {
  try {
    await client.connect();
    const db = client.db("hello");
    const res = await db.command({ ping: 1 }); // 测试数据库是否成功
    console.log("connected", res);
    // 数据的插入
    const userCollection = db.collection("user");
    // limit
    const options: FindOptions = {
      limit: 2, // 获取几条
      skip: 1, // 跳过几条
      sort: {
        age: -1,
      },
      projection: {
        // 投影
        // _id: 0,
        name: 1,
      },
    };
    // options支持链式调用
    const results = await userCollection.find({ age: { $type: "number" } }, options).toArray();
    console.log(results);
  } catch (error) {
    console.error("error", error);
  } finally {
    await client.close();
  }
}

run();
